package me.lwn.auth.security.web.authentication;

import me.lwn.auth.security.utils.LocalMessageSource;
import me.lwn.auth.security.utils.OAuth2EndpointUtils;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.web.authentication.AuthenticationConverter;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

import static me.lwn.auth.security.utils.Constants.*;

public class SmsAuthenticationConverter implements AuthenticationConverter {

    MessageSourceAccessor message = LocalMessageSource.getAccessor();

    @Override
    public Authentication convert(HttpServletRequest request) {

        // type (REQUIRED)
        String type = request.getParameter(SPRING_SECURITY_FORM_LOGIN_TYPE_KEY);
        if (!SPRING_SECURITY_FORM_LOGIN_TYPE_VALUE_SMS.equals(type)) {
            return null;
        }

        MultiValueMap<String, String> parameters = OAuth2EndpointUtils.getParameters(request);

        // mobile (REQUIRED)
        String mobile = parameters.getFirst(SPRING_SECURITY_FORM_MOBILE_KEY);
        if (!StringUtils.hasText(mobile) || parameters.get(SPRING_SECURITY_FORM_MOBILE_KEY).size() != 1) {
            OAuth2EndpointUtils.throwError(OAuth2ErrorCodes.INVALID_REQUEST,
                    message.getMessage("SmsAuthenticationConverter.mobileRequired"), "");
        }

        // code (REQUIRED)
        String code = parameters.getFirst(SPRING_SECURITY_FORM_SMS_CODE_KEY);
        if (!StringUtils.hasText(code) || parameters.get(SPRING_SECURITY_FORM_SMS_CODE_KEY).size() != 1) {
            OAuth2EndpointUtils.throwError(OAuth2ErrorCodes.INVALID_REQUEST,
                    message.getMessage("SmsAuthenticationConverter.codeRequired"), "");
        }

        return new SmsAuthenticationToken(mobile, code);
    }
}
